package cn.mycc.web.controller;

import cn.mycc.domain.Department;
import cn.mycc.domain.Employee;
import cn.mycc.qo.EmployeeQueryObject;
import cn.mycc.qo.PageResult;
import cn.mycc.service.IDepartmentService;
import cn.mycc.service.IEmployeeService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;

import java.util.List;


//处理CRUD请求
@RequestMapping("/employee")
@Controller
public class EmployeeController {

    @Autowired
    private IEmployeeService employeeService;

    @Autowired
    private IDepartmentService departmentService;

//    处理查询所有部门的请求
//    /employee/list 响应HTML格式内容 显示数据库数据内容
    @RequestMapping("/list")
    public String list(Model model, @ModelAttribute("qo")EmployeeQueryObject qo){
        PageResult<Employee> pageResult = employeeService.query(qo);
//        List<Employee> employees = employeeService.getAll();
//        model.addAttribute("employees", employees);
        model.addAttribute("PageResult", pageResult);
//        查询所有部门数据存到model中
        List<Department> departments = departmentService.getAll();
        model.addAttribute("departments", departments);
        return "/employee/list";
    }

//    处理部门删除请求
    @RequestMapping("/delete")
    public String delete(Long id){
        if (id != null){
            employeeService.delete(id);
        }
//        重定向再次查询
        return "redirect:/employee/list";
    }
/*
* 在实际开发过程中
* 有三种方法
* 1.处理方法 (有保存 又修改)
* 2.写一个html界面 (只做保存用)
* 3.写一个jsp界面 (一般不用)
* */

    /*一次新增三次请求*/
//    处理去保存和去修改的请求 (跳转界面) 响应HTML
    @RequestMapping("/input")
    public String input(Long id, Model model){ //去新增时 id为空 去修改事会带着id
        //        查询所有部门数据存到model中
        List<Department> departments = departmentService.getAll();
        model.addAttribute("departments", departments);
        if (id != null){
            model.addAttribute("employee", employeeService.get(id));
        }
        return "/employee/input";
    }

//    处理保存和修改请求  参数在请求体中
    @RequestMapping("/saveOrUpdate")
    public String saveOrUpdate(Employee employee){
        if (employee.getId() == null) {
            employeeService.save(employee); //保存
        }else {
            employeeService.update(employee); //修改
        }
        return "redirect:/employee/list";
    }
}
